<template>
  <div class="box">
    <!-- 顶部数据 -->
    <div class="header">
      <a-row type="flex" align="middle" justify="center">
        <a-col :flex="1" style="text-align: center">
          <div class="num-info">
            {{ countData.allClueNum }}
          </div>

          <div>总线索数量</div>
        </a-col>

        <a-divider
            type="vertical"
            style="height: 20px; background-color: #eee"
        />
        <a-col :flex="1" style="text-align: center">
          <div class="num-info">
            {{ countData.dayInsertNum }}
          </div>
          <div>本日新增数量</div>
        </a-col>
        <a-divider
            type="vertical"
            style="height: 20px; background-color: #eee"
        />
        <a-col :flex="1" style="text-align: center">
          <div class="num-info">
            {{ countData.monthInsertNum }}
          </div>
          <div>本月新增数量</div>
        </a-col>
        <a-divider
            type="vertical"
            style="height: 20px; background-color: #eee"
        />
        <a-col :flex="1" style="text-align: center">
          <div class="num-info">{{ countData.invalidClueNum }}</div>

          <div>
            无效线索数量
            <a-tooltip>
              <template #title>状态为无效线索的总和</template>
              <QuestionCircleOutlined/>
            </a-tooltip>
          </div>
        </a-col>
        <a-divider
            type="vertical"
            style="height: 20px; background-color: #eee"
        />
        <a-col :flex="1" style="text-align: center">
          <div class="num-info">{{ countData.conversionRate }}</div>
          <div>
            本月线索转化率
            <a-tooltip>
              <template #title
              >本月线索转化率 = 本月成交线索数/总线索数
              </template
              >

              <QuestionCircleOutlined/>
            </a-tooltip>
          </div>
        </a-col>
      </a-row>
    </div>

    <a-table
        class="m-t-10"
        :columns="columns"
        :dataSource="dataList"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        row-key="id"
        :row-selection="rowSelection"
    >
      <template #title>
        <div class="flex justify-between header-clue">
          <div class="flex-1">
            <a-form ref="searchForm" layout="vertical">
              <a-row :gutter="8" wrap>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-input
                        placeHolder="搜索客户名称"
                        v-model:value="searchParams.contactName"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-input
                        placeHolder="搜索客户电话"
                        v-model:value="searchParams.contactPhone"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-input
                        placeHolder="搜索公司名称"
                        v-model:value="searchParams.company"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-select
                        style="width: 100%"
                        v-model:value="searchParams.villageId"
                        placeholder="请选择意向项目"
                        :options="optionsBuild"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-select
                        style="width: 100%"
                        v-model:value="searchParams.source"
                        :options="clueSource"
                        placeholder="请选择来源"
                    >
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-select
                        style="width: 100%"
                        v-model:value="searchParams.clueFrom"
                        :options="optionsClueFrom"
                        placeholder="请选择线索来源"
                    >
                    </a-select>
                  </a-form-item>
                </a-col>

                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-select
                        style="width: 100%"
                        v-model:value="searchParams.status"
                        :options="optionsStatus"
                        placeholder="请选择线索状态"
                    >
                    </a-select>
                  </a-form-item>
                </a-col>

                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-range-picker
                        class="w-100p"
                        v-model:value="searchParams.created_time"
                        :valueFormat="dateFormatStr"
                        @change="clueTimeChange"
                    />
                  </a-form-item>
                </a-col>

                <a-col>
                  <a-form-item label="">
                    <a-space>
                      <a-button @click="reset">重置</a-button>
                      <a-button type="primary" @click="getDataList(true)">
                        搜索
                      </a-button>
                    </a-space>
                  </a-form-item>
                </a-col>

                <a-col style="margin-left: auto">
                  <a-space>
                    <a-dropdown>
                      <template #overlay>
                        <a-menu @click="handleMenuClick">
                          <a-menu-item key="1"> Excel导入</a-menu-item>
                          <!-- <a-menu-item key="2"> 
                      搜索企业导入
                    </a-menu-item> -->
                        </a-menu>
                      </template>
                      <a-button type="primary" ghost>导入线索</a-button>
                    </a-dropdown>
                    <a-button type="primary" ghost v-permission="['clueManagement','curd','import']"
                              @click="exportClue">导出线索
                    </a-button>
                    <a-button type="primary" @click="addClue"
                    >+新增线索
                    </a-button
                    >
                  </a-space>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </div>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'contact_name'">
          <span>{{ record.contact_name }}</span>
        </template>
        <template v-if="column.key === 'contact_phone'">
          <template v-if=" record?.format_type == 2 &&record.full_phone">
               <span>{{
                   record.isFullPhone ? record.full_phone : record.contact_phone
                 }}</span>
            <eye-invisible-outlined class="ml-5" v-if="record.isFullPhone"
                                    @click="record.isFullPhone=false"/>
            <eye-outlined class="ml-5" v-if="!record.isFullPhone" @click="record.isFullPhone=true"/>
          </template>
          <template v-else>
            <span> {{ record.contact_phone }}</span>
          </template>

        </template>
        <template v-if="column.key === 'company'">
          <span>{{ record.company || "--" }}</span>
        </template>
        <template v-if="column.key === 'status'">
          <a-tag>{{ record.cluestatus?.name }}</a-tag>
          <a-tag color="red" style="margin-top: 4px" v-if="record.about_expire == true">即将回收
          </a-tag>
        </template>
        <template v-if="column.key === 'clue_from'">
          <span>{{ record.clue_form_txt }}</span>
          <span v-if="record.team_user_name">-{{ record.team_user_name }}</span>
        </template>
        <template v-if="column.key === 'channel_company'">
          <span>{{ record.channel_company_name || '--' }}</span>
        </template>
        <template
            v-if="
            column.key === 'updated_at' ||
            column.key === 'remark' ||
            column.key === 'village_name'
          "
        >
          <span>{{ record[column.key] || "--" }}</span>
        </template>

        <template v-if="column.key === 'follow'">
          <span>{{ record?.followUserInfo?.final_name }}</span>
          <span>{{ record?.followUserInfo?.final_phone }}</span>
        </template>

        <template v-if="column.key === 'requiredArea'">
          <span
          >{{ record.expect_area_min }}-{{ record.expect_area_max }}m²</span
          >
        </template>
        <template v-if="column.key === 'action'">
          <a-button
              type="link"
              @click="toFollow(record.id)"
              v-if="record.is_follow"
          >跟进
          </a-button
          >
          <a-popconfirm
              v-if="recovery_type == 2"
              title="确定回收此线索? "
              ok-text="确定"
              cancel-text="取消"
              @confirm="recoveryClue(record.id)"
          >
            <a-button type="link">回收</a-button>
          </a-popconfirm>
          <a-button type="link" @click="toDetail(record.id)">详情</a-button>
        </template>
      </template>
    </a-table>

    <!-- 导入 -->

    <!-- 新建线索 -->
    <CreateClue :visible="addVisible" @onClose="onClose" :clue-source="clueSource"
                @ok="refreshList"/>

    <!-- 跟进 -->
    <ClueFollow
        :visible="followVisible"
        :id="detailId"
        @onClose="() => (followVisible = false)"
        @back="refreshList"
    />
    <!-- 详情 -->
    <ClueDetail
        :visible="detailVisible"
        :id="detailId"
        @closeDetail="() => (detailVisible = false)"
        @back="refreshList"
    />
  </div>
</template>

<script>
import {EyeInvisibleOutlined, EyeOutlined, QuestionCircleOutlined} from "@ant-design/icons-vue";
import {reactive, ref, toRefs, computed, watch} from "vue";
import {useRoute, useRouter} from "vue-router";
import request from "../../../../common/utils/request";
import ClueDetail from "./ClueDetail.vue";
import ClueFollow from "./ClueFollow.vue";
import {Form, message} from "ant-design-vue";
import CreateClue from "./CreateClue.vue";

const useForm = Form.useForm;
const dateFormatStr = "YYYY-MM-DD";
export default {
  components: {
    EyeOutlined, EyeInvisibleOutlined,
    QuestionCircleOutlined,
    ClueDetail,
    CreateClue,
    ClueFollow,
  },
  props: {
    activeKey: {
      type: String,
      default: "",
    },
    refresh: {
      type: Number,
      default: 0,
    },
    optionsClueFrom: {
      type: Array,
      default: () => [],
    },
    optionsBuild: {
      type: Array,
      default: () => [],
    },
    optionsStatus: {
      type: Array,
      default: () => [],
    },
    clueSource: {
      type: Array,
      default: () => [],
    }
  },
  setup(props) {
    const state = reactive({
      list: [],
      itemList: [],
      isDetail: false,
      countData: {},
      ids: []
    });

    const columns = [
      {
        title: "客户名称",
        key: "contact_name",
        width: "10%",
      },
      {title: "客户电话", key: "contact_phone", width: "10%"},
      {
        title: "公司",
        key: "company",
        width: "10%",
      },
      {
        title: "线索状态",
        key: "status",
        width: 200,
      },
      {
        title: "线索来源",
        key: "clue_from",
        width: 200,
      },
      {
        title: "所属渠道公司",
        key: "channel_company",
        width: 240,
      },
      {
        title: "更新时间",
        key: "updated_at",
        width: 200,
      },

      {
        title: "意向项目",
        key: "village_name",
        width: 200,
      },
      {
        title: "需求面积段",
        key: "requiredArea",
        width: 200,
      },
      {
        title: "备注",
        key: "remark",
        width: 200,
      },
      {
        title: "跟进人员",
        key: "follow",
        width: 200,
      },
      {
        title: "操作",
        key: "action",
        width: 200,
      },
    ];

    const {resetFields, validate, validateInfos} = useForm();
    // modelRef,
    // rulesRef
    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const dataList = ref([]);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));
    const loading = ref(false);

    const $router = useRouter();
    //导入
    const handleMenuClick = (val) => {
      console.log(val.key);
      if (val.key == 1) {
        //EXCEL
        $router.push({name: "importClue"});
      } else {
        //搜索企业
      }
    };

    const searchParams = reactive({
      contactName: "",
      contactPhone: "",
      company: "",
      source: undefined,
      villageId: undefined,
      clueFrom: undefined,
      status: undefined,
      created_time: undefined,
      startDate: undefined,
      endDate: undefined,
    });
    const clueTimeChange = (date) => {
      state.created_time = date;
    };

    const getDataList = (val) => {
      const param = {
        page: page.value,
        pageSize: limit.value,
        //   managerAuth: managerAuth.value,
        type: "all",
      };
      Object.keys(searchParams).forEach((key) => {
        if (key != "created_time") {
          if (searchParams[key]) {
            param[key] = searchParams[key];
          }
        } else {
          if (searchParams[key]) {
            param.startDate = searchParams[key][0];
            param.endDate = searchParams[key][1];
          }
        }
      });

      request
          .get("/org", "/business/clue", param)
          .then((res) => {
            console.log(res);
            dataList.value = res.list.map((item) => {
              return {
                ...item,
                isFullPhone: item.format_type == 1,
              };
            });
            state.countData = res.countData;
            total.value = res.total;
          })
          .finally(() => {
            loading.value = false;
          });
    };

    const handleTableChange = (pager, filters, sorter) => {
      page.value = pager.current;
      limit.value = pager.pageSize;

      getDataList();
    };

    const reset = () => {
      Object.keys(searchParams).forEach((key) => {
        searchParams[key] = undefined;
      });
      console.log("searchParams", searchParams);
      getDataList();
    };

    watch([page, limit], () => {
      getDataList();
    });

    // 获取公海规则
    const recovery_type = ref(1); //1自动 2手动
    const getPoolRules = () => {
      request.get("/org", "/business/clue/getCluePool", {}).then((res) => {
        recovery_type.value = res.list.recovery_type;
        console.log(recovery_type.value);
      });
    };

    const init = () => {
      getPoolRules();
      getDataList();
    };
    watch(
        () => props.activeKey,
        (val) => {
          if (val == "all") {
            init();
          }
        },
        {immediate: true}
    );

    watch(
        () => props.refresh,
        (val) => {
          if (val == 1) {
            init();
          }
        }
    );

    // 新增线索相关
    const addVisible = ref(false);
    const addClue = () => {
      addVisible.value = true;
    };
    const onClose = () => {
      addVisible.value = false;
    };
    const refreshList = () => {
      detailVisible.value = false;
      followVisible.value = false;
      addVisible.value = false;
      getDataList();
    };

    // 回收
    const recoveryClue = (val) => {
      request
          .post("/org", "/business/clue/recoveryPoolClue", {id: val})
          .then((res) => {
            message.success("操作成功！");
            getDataList();
          });
    };

    // 详情
    const detailId = ref(0);
    const detailVisible = ref(false);
    const toDetail = (val) => {
      detailId.value = val;
      detailVisible.value = true;
    };
    // 跟进
    const followVisible = ref(false);
    const toFollow = (val) => {
      detailId.value = val;
      followVisible.value = true;
    };

    const rowSelection = ref({
      onChange: (selectedRowKeys, selectedRows) => {
        state.ids = selectedRowKeys
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      },
      onSelect: (record, selected, selectedRows) => {
        console.log(record, selected, selectedRows);
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        console.log(selected, selectedRows, changeRows);
      },
    });

    // 导出线索
    let timer = null;
    const iframe = document.createElement("iframe");
    const exportClue = () => {
      console.log("导出线索")
      if (timer) {
        message.warn("操作过于频繁，请稍后尝试");
        return;
      }
      let params = {
        type: 'all',
        ids: state.ids
      };
      for (let key in searchParams) {
        if (searchParams[key]) {
          params[key] = searchParams[key];
        }
      }
      console.log(params)
      request
          .post("/org", "/business/clue/import", params)
          .then((res) => {
            iframe.src = res.result.fileUrl;
            iframe.style.display = "none";
            document.body.appendChild(iframe);
            setTimeout(() => {
              document.body.removeChild(iframe);
            }, 1000);
            message.success("导出成功,请等待文件生成");
            timer = setTimeout(() => {
              timer = null;
            }, 20000);
          });
    };


    return {
      ...toRefs(state),
      handleMenuClick,
      addClue,
      columns,
      searchParams,
      addVisible,
      onClose,
      getDataList,
      dataList,
      handleTableChange,
      pagination,
      dateFormatStr,
      reset,
      toDetail,
      toFollow,
      followVisible,
      recoveryClue,
      detailVisible,
      detailId,
      refreshList,
      recovery_type,
      loading,
      clueTimeChange,
      exportClue,
      rowSelection
    };
  },
};
</script>

<style lang="less" scoped>
.box {
  padding: 10px;

  .header-clue {
    padding: 0 16px;
  }

  .header {
    background-color: rgb(240, 242, 245);
    padding: 10px;

    .num-info {
      color: #2681f3;
      font-size: 30px;
      max-width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      word-break: break-all;
    }
  }

  .m-t-10 {
    margin-top: 10px;
  }
}

:deep(.ant-table-title) {
  padding: 0;
}
</style>
